package com.ykht.proj.comsrv.handle;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.SerializationUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ykht.proj.admin.api.entity.SysSocialDetails;
import com.ykht.proj.admin.api.feign.RemoteSysSocialDetailsService;
import com.ykht.proj.common.core.constant.SecurityConstants;
import com.ykht.proj.common.core.constant.enums.LoginTypeEnum;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.comsrv.constant.ComConstant;
import com.ykht.proj.comsrv.entity.VSubscribeMsg;
import com.ykht.proj.comsrv.vo.SubscribeMsg;
import com.ykht.proj.comsrv.vo.SubscribeMsgCouponExpire;
import com.ykht.proj.comsrv.vo.SubscribeMsgCouponTouTiaoExpire;
import com.ykht.proj.coupon.api.feign.RemoteCouponLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * 优惠券过期实现类
 */
@Slf4j
@Component(ComConstant.SUBSCRIBE_MSG_COUPON_EXPIRE_TOUTIAO)
@RefreshScope
@SuppressWarnings("all")
public class SubscribeMsgCouponExpireTouTiaoHandler extends AbstractSubscribeMsgHandler<JSONObject>{

	@Value("${subscribeMsg.couponExpireTouTiao.templateId:MSG12205316ffb0cedb57a62cfa362a60f5a3de5d914573}")
	private String templateId;
	@Value("${subscribeMsg.couponExpireTouTiao.page:/pages/merchant/coupon_detail}")
	private String page;

	@Autowired
	private RemoteCouponLogService remoteCouponLogService;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private RemoteSysSocialDetailsService remoteSysSocialDetailsService;

	@Override
	public VSubscribeMsg checkSend(SubscribeMsg msg) {
		SubscribeMsgCouponTouTiaoExpire tempMsg = (SubscribeMsgCouponTouTiaoExpire)msg;
		VSubscribeMsg vSubscribeMsg = new VSubscribeMsg().selectOne(Wrappers.lambdaQuery(VSubscribeMsg.class)
				.eq(VSubscribeMsg::getPersonId,tempMsg.getPersonId())
				.eq(VSubscribeMsg::getStatus,0)
				.eq(VSubscribeMsg::getSendFlag,0)
				.eq(VSubscribeMsg::getTatId,tempMsg.getCouponId())
				.eq(VSubscribeMsg::getType,msg.getType()));
		Boolean flag = false;
		if(vSubscribeMsg!=null){
			flag = remoteCouponLogService.sendMsgFlag(vSubscribeMsg.getTatId(),vSubscribeMsg.getPersonId(),SecurityConstants.FROM_IN);
		}
		return !flag?null:vSubscribeMsg;
	}

	@Override
	public JSONObject transform(SubscribeMsg tempMsg) {

		String redisAccessToken = "TOUTIAO_ACCESS_TOKEN";

		R<SysSocialDetails> r = remoteSysSocialDetailsService.getOne(LoginTypeEnum.TOUTIAO_DOUYIN_C.getType(), SecurityConstants.FROM_IN);
		SysSocialDetails social = r.getData();

		String app_id = social.getAppId();
		String secret = social.getAppSecret();

		Object access_token =  redisTemplate.opsForValue().get(redisAccessToken);
		if (access_token==null){
			String getAccessToken = "https://developer.toutiao.com/api/apps/token?appid=%s&secret=%s&grant_type=client_credential";
			String access_tokenStr = HttpUtil.get(String.format(getAccessToken, app_id, secret));
			access_token = JSONUtil.parseObj(access_tokenStr).getStr("access_token");
			if (access_token!=null){
				redisTemplate.opsForValue().set(redisAccessToken, JSONUtil.toJsonStr(access_token),4, TimeUnit.MINUTES);
				log.info("请求获取access_token:{}，并存入redis",access_token);
			}
		}else {
			log.info("缓存中获取access_token:{}",access_token);
		}


		SubscribeMsgCouponTouTiaoExpire msg = (SubscribeMsgCouponTouTiaoExpire)tempMsg;
		JSONObject data = JSONUtil.createObj()
				.putOpt("优惠券名称",msg.getCouponName())
				.putOpt("小程序","吃哈哈")
				.putOpt("剩余时间",Duration.between(LocalDateTime.now(),LocalDateTime.parse(msg.getEndTime())).toHours()+"个小时")
				.putOpt("备注",msg.getContent());

		JSONObject o = JSONUtil.createObj().putOpt("access_token",access_token)
				.putOpt("app_id",app_id)
				.putOpt("tpl_id",templateId)
				.putOpt("open_id",msg.getOpenId())
				.putOpt("data",data)
				.putOpt("page",page);
		return o;
	}

	@Override
	public void send(JSONObject data) throws Exception {

		String url = "https://developer.toutiao.com/api/apps/subscribe_notification/developer/v1/notify";
		HttpResponse response = HttpUtil.createPost(url).body(data.toString(), ContentType.JSON.toString()).execute();
		String result = response.body();
		JSONObject r = JSONUtil.parseObj(result);
		Integer err_no = r.getInt("err_no");
		String err_tips = r.getStr("err_tips");
		log.info("发送消息:{}。/t响应:{}",data,result);
		if (err_no != 0) throw new RuntimeException("消息发送失败：" + err_tips);
	}

	@Override
	public void save(VSubscribeMsg vSubscribeMsg,JSONObject data,SubscribeMsg tempMsg) {
		SubscribeMsgCouponTouTiaoExpire msg = (SubscribeMsgCouponTouTiaoExpire)tempMsg;
		vSubscribeMsg.setMsg(data.toString());
		vSubscribeMsg.setPersonId(msg.getPersonId());
		vSubscribeMsg.setOpenId(msg.getOpenId());
		vSubscribeMsg.setTatId(msg.getCouponId());
		vSubscribeMsg.setType(msg.getType());
		vSubscribeMsg.setStatus(0);
		vSubscribeMsg.setSendFlag(1);
		vSubscribeMsg.setCreateTime(LocalDateTime.now());
		vSubscribeMsg.updateById();
	}


}
